package com.easy.controller;

import com.easy.bean.User;
import com.easy.common.CommonResult;
import com.easy.service.IUserService;
import com.easy.utils.DigestUtil;
import com.easy.utils.JWTUtil;
import com.easy.utils.Page;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

@RestController
public class UserController {

    @Autowired
    IUserService userS;


    private final ConcurrentHashMap<String, CaptchaInfo> captchaMap = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    private static class CaptchaInfo {
        String code;
        ScheduledFuture<?> future;

        CaptchaInfo(String code, ScheduledFuture<?> future) {
            this.code = code;
            this.future = future;
        }
    }

    @PostMapping("/dologin")
    public CommonResult doLogin(@RequestBody User user){
        boolean bool = verification(user.getCode(),user.getKey());
        if(!bool){
            return CommonResult.fail(403,"验证码错误");
        }
        String token = userS.doLogin(user);
        if(token == null){
            return CommonResult.fail(403,"账号或密码错误");
        }else{
            return CommonResult.success(200,"登陆成功",token);
        }
    }

    @GetMapping("/checkToken")
    public CommonResult checkToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(token!=null && JWTUtil.verifyToken(token)){
            return CommonResult.success();
        }
        return CommonResult.fail();
    }


    @GetMapping("/decodetoken")
    public CommonResult decodeToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Map map = userS.decode(token);
        return CommonResult.success(map);
    }


    //获取验证码
    @ResponseBody
    @GetMapping("/captcha")
    public CommonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // gif类型
        //GifCaptcha captcha = new GifCaptcha(130, 48);

        // 中文类型
        //ChineseCaptcha captcha = new ChineseCaptcha(130, 48);

        // 中文gif类型
        //ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48);
        // 算术类型
        //ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        // png类型
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);

        /**验证码字符类型
         TYPE_DEFAULT 数字和字母混合
         TYPE_ONLY_NUMBER 纯数字
         TYPE_ONLY_CHAR 纯字母
         TYPE_ONLY_UPPER 纯大写字母
         TYPE_ONLY_LOWER 纯小写字母
         TYPE_NUM_AND_UPPER  数字和大写字母**/
        captcha.setCharType(Captcha.TYPE_DEFAULT);//设置纯数字验证码
        // 设置内置字体
//        captcha.setFont(Captcha.FONT_1);
        // 设置系统字体
//        captcha.setFont(new Font("楷体", Font.PLAIN, 28));
        //验证码 VUL
        String verCode = captcha.text().toLowerCase();
        //uuid KEY
        String key ="captcha:"+ UUID.randomUUID().toString();
        // 存入redis并设置过期时间为2分钟
//        stringRedisTemplate.opsForValue().set(key, verCode, 2, TimeUnit.MINUTES);
//        // 将key和base64返回给前端
//        Map<String,String> map=new HashMap<>();
//        map.put("key", key);
//        map.put("image", captcha.toBase64());
//        return new CommonResult(200,"success",map);

        // 安排验证码过期任务
        Runnable expireTask = () -> captchaMap.remove(key);
        ScheduledFuture<?> future = scheduler.schedule(expireTask, 2, TimeUnit.MINUTES);

        CaptchaInfo info = new CaptchaInfo(verCode, future);
        captchaMap.put(key, info);
        Map<String,String> map=new HashMap<>();
        map.put("key", key);
        map.put("image", captcha.toBase64());
        return CommonResult.success(200,"success",map);
    }

    //验证验证码
    public Boolean verification(String verCode,String verKey){
//        // 获取redis中的验证码
//        String redisCode = stringRedisTemplate.opsForValue().get(verKey);
//        // 判断验证码
//        if (verCode==null || !redisCode.equals(verCode.trim().toLowerCase())) {
//            return false;
//        }
//        return true;
        CaptchaInfo info = captchaMap.get(verKey);
        if (info == null || !info.code.equals(verCode.trim().toLowerCase())) {
            return false;
        }
        // 可选：验证成功后立即移除验证码，防止重复使用
        captchaMap.remove(verKey);
        return true;
    }

    @GetMapping("user")
    public CommonResult getUser(User user, Page page){
        List<User> list = userS.getUser(user,page);
        int count = userS.getUserCount(user);
        HashMap map = new HashMap<>();
        map.put("list", list);
        map.put("count", count);
        return CommonResult.success(map);
    }

    @DeleteMapping("user/{id}")
    public CommonResult delUser(@PathVariable int id){
        int res = userS.delUser(id);
        return CommonResult.success(res);
    }

    @PostMapping("user")
    public CommonResult addUser(@RequestBody User user){
        user.setPassword(DigestUtil.randomDigest(user.getPassword()));
        userS.addUser(user);
        user = userS.getUserByID(user.getId());
        return CommonResult.success(user);
    }

    @PutMapping("user")
    public CommonResult editUser(@RequestBody User user){
        user.setPassword(DigestUtil.randomDigest(user.getPassword()));
        userS.editUser(user);
        user = userS.getUserByID(user.getId());
        return CommonResult.success(user);
    }

    @GetMapping("userbyid/{id}")
    public CommonResult getUserByID(@PathVariable int id){
        return CommonResult.success(userS.getUserByID(id));
    }

    @GetMapping("checkOldPassword")
    public CommonResult checkOldPassword(User user){
        User user_data = userS.getUserByID(user.getId());
        if(user_data != null){
            boolean bool = DigestUtil.decode(user.getOldPassword(),user_data.getPassword());
            if(bool){
                return CommonResult.success();
            }
        }
        return CommonResult.fail();
    }
}
